package com.rtsapp.server.benchmark.runner.channel;

import com.rtsapp.server.benchmark.ITestCaseIterator;
import com.rtsapp.server.benchmark.runner.ICommandCaseHandlerFactory;
import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import com.rtsapp.server.network.protocol.crypto.IAppChannelInitializer;
import com.rtsapp.server.network.protocol.crypto.client.ClientRSAHandshake;
import com.rtsapp.server.network.protocol.crypto.client.ClientRSAHandshakeKey;
import com.rtsapp.server.network.protocol.crypto.server.ServerRSAHandshake;
import com.rtsapp.server.network.protocol.crypto.server.ServerRSAHandshakeKey;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;

import java.util.Map;

/**
 * 加密
 */
public class CryptoCommandCaseChannelInitializer extends CommandCaseChannelInitializer {

    private static final Logger LOG = LoggerFactory.getLogger( CryptoCommandCaseChannelInitializer.class );

    //RSA连接握手的Key
    private final ClientRSAHandshakeKey handshakeKey;


    public CryptoCommandCaseChannelInitializer(ICommandCaseHandlerFactory commandCaseHandlerFactory, EventLoopGroup eventLoop, ITestCaseIterator iterator, Map<String, Object> contxt, ClientRSAHandshakeKey handshakeKey) {
        super(commandCaseHandlerFactory, eventLoop, iterator, contxt);
        this.handshakeKey = handshakeKey;
    }
    

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {

        try {
            ClientRSAHandshake handshake = new ClientRSAHandshake(ch, new OriginChannelInitializer(), handshakeKey);
            handshake.start();
        }catch ( Throwable ex ){
            LOG.error(ex, "CryptoCommandChannelInitializer int error");
            ch.close();
        }
    }

    private void originInitChannel( SocketChannel ch ) throws Exception{
        super.initChannel(ch);
    }

    public class OriginChannelInitializer implements IAppChannelInitializer {

        @Override
        public void initChannel(SocketChannel ch)  throws Exception {
            CryptoCommandCaseChannelInitializer.this.originInitChannel( ch );
        }

    }

}
